<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\admin\model;
use think\Model;
use think\File;
class Article extends Model{
    
protected static function init()
    {
        Article::event('before_insert', function ($data) {
            
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('pic');
            
            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $info = $file->move(ROOT_PATH . '/uploads/images');
               
                if($info){
             
                    $data['pic']='/uploads/images/'.$info->getSaveName();
                    
                    return $data;
                
                }else{

                    echo $file->getError();
                }
            }
            else{
                return $data;
            }
           
         });
        
        
        Article::event('before_update', function ($data) {
            
            $file = request()->file('pic');
           
            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $id=$data['id'];
                $dataold=ROOT_PATH .Article::find($id)['pic'];
                if (!unlink($dataold))
                {
                echo ("Error deleting $dataold");
                }
              else
                {
                    $info = $file->move(ROOT_PATH . '/uploads/images');

                    if($info){

                        $data['pic']='/uploads/images/'.$info->getSaveName();
                    

                    }else{

                        echo $info->getError();
                    }
                }     
              
            }
            else{
                return $data;
            }
         });
         
         
        
         Article::event('before_delete', function($data){
             $id=$data['id'];
             $filename= $_SERVER['DOCUMENT_ROOT'].Article::find($id)['pic'];
             if(!unlink($filename)){
                  echo $filename ."删除失败";
             } else {
                  
             }
         });

    }
}